<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 自定义组件，标题 -->
      <PageTitle :show-before="true">
        <template v-slot:before>
          <h2>{{ $t('route.roleManagement') }}</h2>
        </template>
        <template v-slot:after>
          <el-button type="primary" icon="el-icon-edit" size="meduim" :disabled="!checkPermission('roleManagement-add')" @click="addRole('add',0)">{{ $t('button.add') }}</el-button>
        </template>
      </PageTitle>
      <!-- 数据表 -->
      <el-table v-loading="downloadLoading" border :data="list" max-height="700px" style="margin-top: 20px;">
        <el-table-column label="ID" align="center" sortable width="60" prop="id" />
        <el-table-column v-if="languages==='zh'" :label="$t('table.roleName')" align="center" prop="name" />
        <el-table-column v-if="languages==='en'" :label="$t('table.roleName')" align="center" prop="name_en[1].name" />
        <el-table-column v-if="languages==='zh'" :label="$t('table.describe')" align="center" prop="descr" />
        <el-table-column v-if="languages==='en'" :label="$t('table.describe')" align="center" prop="name_en[1].remarks" />
        <el-table-column :label="$t('table.actions')" align="center">
          <template slot-scope="{row}">
            <el-button type="primary" icon="el-icon-edit" size="mini" :disabled="!checkPermission('roleManagement-edit')" @click="addRole('edit',row)">{{ $t('button.edit') }}</el-button>
            <el-button type="success" icon="el-icon-warning-outline" size="mini" :disabled="!checkPermission('roleManagement-set')" @click="openRole(row)">{{ $t('button.Configurepermissions') }}</el-button>
            <el-button size="mini" :disabled="!checkPermission('roleManagement-del')" @click="delRole(row)">{{ $t('button.delete') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <el-row type="flex" align="middle" style="margin-left: 20px;">
      <el-pagination background layout="total,prev,pager,next" :total="count" :page-size="query.limit" :current-page="query.page" @current-change="changPage" />
    </el-row>
    <!-- 添加 -->
    <el-dialog :visible="showDialog" :title="dialogTitle" @close="btnCanle">
      <el-form ref="ruleForm" :model="formData" :rules="rules" label-width="150px">
        <el-form-item :label="$t('table.zhTitle')" prop="name">
          <el-input v-model="formData.name" style="width: 50%;" :placeholder="$t('table.enterThe')+' '+$t('table.zhTitle')" />
        </el-form-item>
        <el-form-item :label="$t('table.enTitle')" prop="Enname">
          <el-input v-model="formData.name_en[1].name" style="width: 50%;" :placeholder="$t('table.enterThe')+' '+$t('table.enTitle')" />
        </el-form-item>
        <el-form-item :label="$t('table.zhdescribe')" prop="descr">
          <el-input v-model="formData.descr" style="width: 50%;" :placeholder="$t('table.enterThe')+' '+$t('table.zhdescribe')" />
        </el-form-item>
        <el-form-item :label="$t('table.endescribe')" prop="descr">
          <el-input v-model="formData.name_en[1].remarks" style="width: 50%;" :placeholder="$t('table.enterThe')+' '+$t('table.endescribe')" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="btnCanle">{{ $t('button.cancel') }}</el-button>
        <el-button type="primary" @click="btnOk">{{ $t('button.confirm') }}</el-button>
      </div>
    </el-dialog>
    <!-- 配置权限 -->
    <el-dialog :visible="roleShowDialog" :title="$t('button.Configurepermissions')" @close="btnCanleRole">
      <el-tree ref="permTree" :data="permData" :props="defaultProps" :show-checkbox="true" :default-checked-keys="selectCheck" node-key="id" :check-strictly="true" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="btnCanleRole">{{ $t('button.cancel') }}</el-button>
        <el-button type="primary" @click="btnPermOK">{{ $t('button.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getGroupAdminList, addGroupAdmin, delGroupAdmin, getMenuList, addRole } from '@/api/user'
import { tranListTotreeData } from '@/utils'
import Cookie from 'js-cookie'
export default {
  data() {
    return {
      languages: Cookie.get('language'),
      downloadLoading: false,
      list: [],
      count: 0,
      query: {
        bid: 0,
        page: 1,
        limit: 10
      },
      showDialog: false,
      dialogTitle: this.$t('table.addRole'),
      formData: {
        bid: 0,
        name: '',
        id: undefined,
        descr: '',
        is_show: 1,
        name_en: [
          { name: '', languages: 'zh', remarks: '' },
          { name: '', languages: 'en', remarks: '' }
        ]
      },
      rules: {
        name: [{ required: true, message: this.$t('table.zhTitle') + this.$t('prompt.noEmpty'), trugger: 'blur' }]
      },
      roleShowDialog: false,
      permData: [],
      defaultProps: {
        label: 'name'
      },
      selectCheck: [], // 定义一个数组来接收 已经选中的节点
      roleId: undefined// 用来记录分配角色的id
    }
  },
  created() {
    this.getGroup()
  },
  methods: {
    // 获取角色列表
    async getGroup() {
      this.downloadLoading = true
      const { count, list } = await getGroupAdminList(this.query)
      this.count = count
      this.list = list
      this.downloadLoading = false
    },
    // 分页
    changPage(newPage) {
      this.query.page = newPage
      this.getGroup()
    },
    // 打开新增编辑
    addRole(type, row) {
      if (type === 'add') {
        this.dialogTitle = this.$t('table.addRole')
        this.formData.name = ''
        this.formData.id = undefined
        this.formData.descr = ''
        for (let i = 0; i < this.formData.name_en.length; i++) {
          this.formData.name_en[i].name = ''
          this.formData.name_en[i].remarks = ''
        }
        this.showDialog = true
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      } else if (type === 'edit') {
        this.dialogTitle = this.$t('table.editRole')
        this.formData.name = row.name
        this.formData.id = row.id
        this.formData.descr = row.descr
        for (let i = 0; i < this.formData.name_en.length; i++) {
          for (let j = 0; j < row.name_en.length; j++) {
            if (this.formData.name_en[i].languages === row.name_en[j].languages) {
              this.formData.name_en[i].name = row.name_en[j].name
              this.formData.name_en[i].remarks = row.name_en[i].remarks
            }
          }
        }
        this.showDialog = true
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      }
    },
    // 确定提交
    async btnOk() {
      try {
        this.formData.name_en[0].name = this.formData.name
        this.formData.name_en[0].remarks = this.formData.descr
        await this.$refs.ruleForm.validate()
        await addGroupAdmin(this.formData)
        this.btnCanle()
        this.getGroup()
        this.$message.success(this.$t('prompt.success'))
      } catch (error) {
        this.$message.error(this.$t('prompt.failed'))
      }
    },
    // 删除
    async delRole(row) {
      try {
        await this.$confirm(this.$t('prompt.deleteit'))
        await delGroupAdmin(row)
        this.getGroup()
        this.$message.success(this.$t('prompt.deletesuccess'))
      } catch (error) {
        this.$message.error(this.$t('prompt.deletefailed'))
      }
    },
    // 取消
    btnCanle() {
      this.dialogTitle = this.$t('table.addRole')
      this.formData.name = ''
      this.formData.id = undefined
      this.formData.descr = ''
      this.showDialog = false
    },
    // 取消权限配置
    btnCanleRole() {
      this.roleId = undefined
      this.selectCheck = null
      this.roleShowDialog = false
    },
    // 打开权限
    async openRole(row) {
      await this.getMenu()
      this.roleId = row.id
      this.selectCheck = row.MR
      this.roleShowDialog = true
    },
    // // 获取权限菜单
    async getMenu() {
      const { list } = await getMenuList(this.query)
      this.permData = list
      // 调用自定义的树状数组函数，处理获取的数组
      if (this.permData != null) {
        this.permData = tranListTotreeData(this.permData, 0)
      }
    },
    // 确定配置权限
    async btnPermOK() {
      // 调用el-tree的方法
      console.log(this.$refs.permTree.getCheckedKeys())
      const data = {
        role_id: this.roleId,
        menu_ids: this.$refs.permTree.getCheckedKeys()
      }
      try {
        await addRole(data)
        this.getGroup()
        this.roleShowDialog = false
        this.$message.success(this.$t('prompt.success'))
      } catch (error) {
        this.$message.error(this.$t('prompt.failed'))
      }
    }
  }
}
</script>
